package com.lancoo.answer.widget.combinationView;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Looper;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.lancoo.answer.R;
import com.lancoo.answer.manager.MediaManager;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.util.DpUtils;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.paperUtils.ChildRightOrWrongJudgeUtils;
import com.lancoo.answer.widget.span.MatchAnwerFillCharSpan;
import com.lancoo.answer.widget.span.MatchAnwerSpan;
import com.lancoo.answer.widget.span.view.MatchFillCallBack;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;

import java.util.List;


/**
 * Created by pengmi on 2021/12/7 11:45
 * Description:段落匹配小题题干样式
 */
public class MatchQueseBodyView extends RelativeLayout implements View.OnClickListener{

    private static final String TAG = "MatchQueseBodyView";
    private TextView tv_queseBody;
    private ImageView img_horn;
    private long subTime;
    private MediaManager mediaManager;
    private int showIndex=0;//默认选中答题点序号
    private MatchFillCallBack callBack;
    private int trainType=2;//0--作答样式，1--已提交，2--查看评阅

    public MatchQueseBodyView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public MatchQueseBodyView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MatchQueseBodyView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context){
        LayoutInflater.from(context).inflate(R.layout.ev_layout_quese_body_match_view,this);
        tv_queseBody = findViewById(R.id.tv_quese_body);
        int dp12= DpUtils.dip2px(context,12);
        tv_queseBody.setLineSpacing(dp12,1);
        tv_queseBody.setBackgroundResource(R.drawable.ev_shape_5_corners_f7_bg);
        img_horn = findViewById(R.id.img_horn);
        findViewById(R.id.child_audio_view).setVisibility(GONE);
        tv_queseBody.setPadding(dp12,dp12,dp12,dp12);
        adjustFontSize();
    }

    public void initData(Child child){
        if(child==null){
            Log.e(TAG,"child is null");
            return;
        }
        String childAsk = child.getChildAsk();
        if(childAsk==null){
            childAsk="";
        }
        Document document = Jsoup.parse(childAsk);
        List<Node> nodes = document.body().childNodes();
        SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
        int index=0;
        for (int i = 0; i < nodes.size(); i++) {
            Node node = nodes.get(i);
            if(node instanceof Element){
                Element element= (Element) node;
                List<Node> nodes1 = element.childNodes();
                for (Node node1:nodes1){
                    String s1 = node1.nodeName();
                    String aClass2 = node1.attr("class");
                    Log.e(TAG,"aClass1 size:"+index);
                    int type;//0-未填写，1-做对，2-做错
                    if(TextUtils.equals("span",s1)&&TextUtils.equals(aClass2,"znbkblank")){
                        spannableStringBuilder.append(" ");
                        List<Item> itemList = child.getItemList();
                        if(itemList==null){
                            return;
                        }
                        if(trainType==2){
                            Item item =itemList.get(index);
                            String stuAnswer = item.getStuAnswer();
                            if(TextUtils.isEmpty(stuAnswer)){
                                type=0;
                            }else{
                                int state = ChildRightOrWrongJudgeUtils.judateItemAnwerState(item);
                                if(state==1){
                                    type=1;
                                }else{
                                    type=2;
                                }
                            }
                            String itemAnswer = child.getItemList().get(index).getItemAnswer();
                            switch (type){
                                case 0:
                                    SpannableString ss1=new SpannableString("未");
                                    setOnClick(ss1,index);
                                    MatchAnwerSpan mas1=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas1.setDrawableLineType(1);
                                    mas1.setmText("未");
                                    mas1.setEndFill(false);
                                    mas1.setStartFill(true);
                                    mas1.setAnswerPointIndex(index);
                                    ss1.setSpan(mas1,0,ss1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss1);

                                    SpannableString ss2=new SpannableString("填");
                                    setOnClick(ss2,index);
                                    MatchAnwerSpan mas2=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas2.setDrawableLineType(1);
                                    mas2.setmText("填");
                                    mas2.setEndFill(false);
                                    mas2.setStartFill(false);
                                    mas2.setAnswerPointIndex(index);
                                    ss2.setSpan(mas2,0,ss2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss2);

                                    SpannableString ss3=new SpannableString("写");
                                    setOnClick(ss3,index);
                                    MatchAnwerSpan mas3=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas3.setDrawableLineType(1);
                                    mas3.setmText("写");
                                    mas3.setEndFill(false);
                                    mas3.setStartFill(false);
                                    mas3.setAnswerPointIndex(index);
                                    ss3.setSpan(mas3,0,ss3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss3);

                                    SpannableString ss4=new SpannableString("(");
                                    setOnClick(ss4,index);
                                    MatchAnwerSpan mas4=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas4.setDrawableLineType(2);
                                    mas4.setmText("(");
                                    mas4.setEndFill(false);
                                    mas4.setStartFill(false);
                                    mas4.setAnswerPointIndex(index);
                                    ss4.setSpan(mas4,0,ss4.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss4);

                                    SpannableString ss5=new SpannableString(""+itemAnswer);
                                    setOnClick(ss5,index);
                                    MatchAnwerSpan mas5=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas5.setDrawableLineType(2);
                                    mas5.setmText(itemAnswer);
                                    mas5.setEndFill(false);
                                    mas5.setStartFill(false);
                                    mas5.setAnswerPointIndex(index);
                                    ss5.setSpan(mas5,0,ss5.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss5);

                                    SpannableString ss6=new SpannableString(")");
                                    setOnClick(ss6,index);
                                    MatchAnwerSpan mas6=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas6.setDrawableLineType(2);
                                    mas6.setmText(")");
                                    mas6.setEndFill(true);
                                    mas6.setStartFill(false);
                                    mas6.setAnswerPointIndex(index);
                                    ss6.setSpan(mas6,0,ss6.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss6);

                                    break;
                                case 1:
                                    SpannableString ss11=new SpannableString("1");
                                    setOnClick(ss11,index);
                                    MatchAnwerSpan mas11=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas11.setDrawableLineType(2);
                                    mas11.setmText("\t");
                                    mas11.setEndFill(false);
                                    mas11.setStartFill(true);
                                    mas11.setAnswerPointIndex(index);
                                    ss11.setSpan(mas11,0,ss11.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss11);

                                    SpannableString ss12=new SpannableString("1");
                                    setOnClick(ss12,index);
                                    MatchAnwerSpan mas12=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas12.setDrawableLineType(2);
                                    mas12.setmText("\t");
                                    mas12.setEndFill(false);
                                    mas12.setStartFill(false);
                                    mas12.setAnswerPointIndex(index);
                                    ss12.setSpan(mas12,0,ss12.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss12);

                                    SpannableString ss13=new SpannableString(""+itemAnswer);
                                    setOnClick(ss13,index);
                                    MatchAnwerSpan mas13=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas13.setDrawableLineType(2);
                                    mas13.setmText(itemAnswer);
                                    mas13.setEndFill(false);
                                    mas13.setStartFill(false);
                                    mas13.setAnswerPointIndex(index);
                                    ss13.setSpan(mas13,0,ss13.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss13);

                                    SpannableString ss14=new SpannableString("1");
                                    setOnClick(ss14,index);
                                    MatchAnwerSpan mas14=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas14.setDrawableLineType(2);
                                    mas14.setmText("\t");
                                    mas14.setEndFill(false);
                                    mas14.setStartFill(false);
                                    mas14.setAnswerPointIndex(index);
                                    ss14.setSpan(mas14,0,ss14.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss14);
                                    SpannableString ss15=new SpannableString("1");
                                    setOnClick(ss15,index);
                                    MatchAnwerSpan mas15=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas15.setDrawableLineType(2);
                                    mas15.setmText("\t");
                                    mas15.setEndFill(true);
                                    mas15.setStartFill(false);
                                    mas15.setAnswerPointIndex(index);
                                    ss15.setSpan(mas15,0,ss15.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss15);
                                    break;
                                case 2:
                                    SpannableString ss21=new SpannableString("1");
                                    setOnClick(ss21,index);
                                    MatchAnwerSpan mas21=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas21.setDrawableLineType(2);
                                    mas21.setmText("\t");
                                    mas21.setEndFill(false);
                                    mas21.setStartFill(true);
                                    mas21.setAnswerPointIndex(index);
                                    ss21.setSpan(mas21,0,ss21.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss21);

                                    SpannableString ss22=new SpannableString("A");
                                    setOnClick(ss22,index);
                                    MatchAnwerSpan mas22=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas22.setDrawableLineType(1);
                                    mas22.setmText(item.getStuAnswer());
                                    mas22.setEndFill(false);
                                    mas22.setStartFill(false);
                                    mas22.setAnswerPointIndex(index);
                                    ss22.setSpan(mas22,0,ss22.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss22);

                                    SpannableString ss231=new SpannableString("(");
                                    setOnClick(ss231,index);
                                    MatchAnwerSpan mas231=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas231.setDrawableLineType(2);
                                    mas231.setmText("(");
                                    mas231.setEndFill(false);
                                    mas231.setStartFill(false);
                                    mas231.setAnswerPointIndex(index);
                                    ss231.setSpan(mas231,0,ss231.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss231);

                                    SpannableString ss23=new SpannableString(""+itemAnswer);
                                    setOnClick(ss23,index);
                                    MatchAnwerSpan mas23=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas23.setDrawableLineType(2);
                                    mas23.setmText(itemAnswer);
                                    mas23.setEndFill(false);
                                    mas23.setStartFill(false);
                                    mas23.setAnswerPointIndex(index);
                                    ss23.setSpan(mas23,0,ss23.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss23);

                                    SpannableString ss232=new SpannableString(")");
                                    setOnClick(ss232,index);
                                    MatchAnwerSpan mas232=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas232.setDrawableLineType(2);
                                    mas232.setmText(")");
                                    mas232.setEndFill(false);
                                    mas232.setStartFill(false);
                                    mas232.setAnswerPointIndex(index);
                                    ss232.setSpan(mas232,0,ss232.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss232);

                                    SpannableString ss24=new SpannableString("1");
                                    setOnClick(ss24,index);
                                    MatchAnwerSpan mas24=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                                    mas24.setDrawableLineType(2);
                                    mas24.setmText("\t");
                                    mas24.setEndFill(true);
                                    mas24.setStartFill(false);
                                    mas24.setAnswerPointIndex(index);
                                    ss24.setSpan(mas24,0,ss24.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    spannableStringBuilder.append(ss24);

                            }
                        }else{
                            String itemAnswer = itemList.get(index).getStuAnswer();
                            if(TextUtils.isEmpty(itemAnswer)){
                                itemAnswer=" ";
                            }
                            SpannableString ss11=new SpannableString("1");
                            setOnClick(ss11,index);
                            MatchAnwerSpan mas11=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                            mas11.setDrawableLineType(4);
                            mas11.setmText("\t");
                            mas11.setEndFill(false);
                            mas11.setStartFill(true);
                            mas11.setAnswerPointIndex(index);
                            ss11.setSpan(mas11,0,ss11.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableStringBuilder.append(ss11);

                            SpannableString ss12=new SpannableString("1");
                            setOnClick(ss12,index);
                            MatchAnwerSpan mas12=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                            mas12.setDrawableLineType(4);
                            mas12.setmText("\t");
                            mas12.setEndFill(false);
                            mas12.setStartFill(false);
                            mas12.setAnswerPointIndex(index);
                            ss12.setSpan(mas12,0,ss12.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableStringBuilder.append(ss12);

                            SpannableString ss13=new SpannableString(""+itemAnswer);
                            setOnClick(ss13,index);
                            MatchAnwerFillCharSpan mas13=new MatchAnwerFillCharSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                            mas13.setDrawableLineType(4);
                            mas13.setmText(itemAnswer);
                            mas13.setEndFill(false);
                            mas13.setStartFill(false);
                            mas13.setAnswerPointIndex(index);
                            ss13.setSpan(mas13,0,ss13.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableStringBuilder.append(ss13);

                            SpannableString ss14=new SpannableString("1");
                            setOnClick(ss14,index);
                            MatchAnwerSpan mas14=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                            mas14.setDrawableLineType(4);
                            mas14.setmText("\t");
                            mas14.setEndFill(false);
                            mas14.setStartFill(false);
                            mas14.setAnswerPointIndex(index);
                            ss14.setSpan(mas14,0,ss14.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableStringBuilder.append(ss14);
                            SpannableString ss15=new SpannableString("1");
                            setOnClick(ss15,index);
                            MatchAnwerSpan mas15=new MatchAnwerSpan(tv_queseBody.getContext(),tv_queseBody.getPaint());
                            mas15.setDrawableLineType(4);
                            mas15.setmText("\t");
                            mas15.setEndFill(true);
                            mas15.setStartFill(false);
                            mas15.setAnswerPointIndex(index);
                            ss15.setSpan(mas15,0,ss15.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableStringBuilder.append(ss15);
                        }

                        spannableStringBuilder.append(" ");
                        index++;
                    }else{
                        spannableStringBuilder.append(Html.fromHtml(node1.outerHtml()));

                    }
                }
            }else{
                SpannableString spannableString=new SpannableString(Html.fromHtml(node.outerHtml()));
                spannableString.setSpan(new ForegroundColorSpan(0xff333333),0,spannableString.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableStringBuilder.append(spannableString);
            }


        }
        tv_queseBody.clearComposingText();
        tv_queseBody.setText("");
        tv_queseBody.setText(spannableStringBuilder);

        MatchAnwerSpan[] spans = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), MatchAnwerSpan.class);
        for (MatchAnwerSpan span : spans) {
            span.setUnderLine(span.getAnswerPointIndex() == showIndex);
        }
        MatchAnwerFillCharSpan[] spans1 = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), MatchAnwerFillCharSpan.class);
        for (MatchAnwerFillCharSpan span : spans1) {
            span.setUnderLine(span.getAnswerPointIndex() == showIndex);
        }
        tv_queseBody.setMovementMethod(new LinkMovementMethod());
        tv_queseBody.requestLayout();
    }

    private void setOnClick(SpannableString spannableString,final int position){
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Log.e(TAG,"ClickableSpan onClick");
                showIndex=position;
                callBack.onClick(position);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                Log.e(TAG,"updateDrawState");
                updateCurrentShowIndex(position);
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#333333"));   //设置字体颜色
                ds.setUnderlineText(true);    //设置是否显示下划线
                ds.clearShadowLayer();   //阴影
            }
        },0,spannableString.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }


    public void setCallBack(MatchFillCallBack callBack){
        this.callBack=callBack;

    }


    public void pause(){
        Log.e(TAG,"pause");
        if(mediaManager!=null){
            mediaManager.pause();
        }
        showPlayState(false);
    }

    public void release(){
        if(mediaManager!=null){
            mediaManager.release();
        }
    }


    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-subTime<500){
            return;
        }
        subTime= System.currentTimeMillis();

        if(mediaManager==null||!mediaManager.isPlay()){
            startPlayRecordSound();
            showPlayState(true);
        }else{
            showPlayState(false);
            mediaManager.pause();
        }
    }


    private void showPlayState(boolean isPlaying){
        if( Looper.myLooper() != Looper.getMainLooper()){
            return;
        }
        if(img_horn!=null&&img_horn.getVisibility()== View.VISIBLE){
            if(isPlaying){
                img_horn.setBackground(null);
                ((AnimationDrawable)img_horn.getDrawable()).start();
            }else{
                ((AnimationDrawable)img_horn.getDrawable()).stop();
                ((AnimationDrawable)img_horn.getDrawable()).selectDrawable(0);
            }
        }
    }


    private void startPlayRecordSound(){
        if(mediaManager==null){
            mediaManager=new MediaManager(getContext());
        }
        String url="";
        mediaManager.setUpMedia(url, new MediaManager.OnPlayListener() {
            @Override
            public void onComplete() {
                showPlayState(false);
            }

            @Override
            public void onStartError() {
                showPlayState(false);
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
                showPlayState(false);
            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                if(mediaManager!=null){
                    mediaManager.start();
                }
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.e(TAG,"onBufferingUpdate:"+percent);
            }
        });
    }


    public void updateCurrentShowIndex(int showIndex){
        Log.e(TAG,"updateCurrentShowIndex"+showIndex);
        SpannableString text=new SpannableString(tv_queseBody.getText());
        MatchAnwerSpan[] spans = text.getSpans(0, text.length(), MatchAnwerSpan.class);
        for (MatchAnwerSpan span : spans) {
            span.setUnderLine(span.getAnswerPointIndex() == showIndex);
        }
        MatchAnwerFillCharSpan[] spans1 = text.getSpans(0, text.length(), MatchAnwerFillCharSpan.class);
        for (MatchAnwerFillCharSpan span : spans1) {
            span.setUnderLine(span.getAnswerPointIndex() == showIndex);
        }
        tv_queseBody.requestLayout();
        this.showIndex=showIndex;

    }

    /**
     *设置默认加载小题序号，须在initChild之前调用
     */
    public void setShowIndex(int showIndex){
       this. showIndex=showIndex;
    }

    public int getShowIndex(){
        return showIndex;
    }

    public void setTrainType(int trainType){
        this.trainType=trainType;
    }

    public void adjustFontSize(){
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(tv_queseBody,15);
    }

}
